<script setup lang="ts">
import DrawerModal from "@/components/drawer-modal/index.vue";

import { inject, reactive, watch } from "vue";
import { WS } from "@/pages/room/ws/ws.ts";
import { RoomInfo } from "@/pages/room/model.ts";
import { useDialog, useMessage } from "naive-ui";
import {
    ROOM_NAME_PATTERN, ROOM_NAME_PATTERN_TIP,
    ROOM_PASSWORD_PATTERN,
    ROOM_PASSWORD_PATTERN_TIP
} from "@/pages/room/constant/validation-constants.ts";


const props = defineProps<{
    room: RoomInfo
}>();

const dialog = useDialog();
const message = useMessage();

const ws = inject("ws") as WS;

const data = reactive({
    visible: false,
    name: "",
    url: "",
    password: "",
});

watch(() => props.room, value => {
    data.name = value.name;
    data.url = value.video.url || "";
    data.password = "";
}, { immediate: true });


function handlePlayVideo() {
    ws.emit("video.change", {
        details: {
            url: data.url
        }
    });
    data.visible = false;
}

function handleModifyName() {
    const name = data.name;
    if (!ROOM_NAME_PATTERN.test(name)) {
        return message.warning(ROOM_NAME_PATTERN_TIP);
    }
    ws.emit("room.modify.name", {
        details: {
            name
        }
    });
    data.name = "";
}

function handleModifyPassword() {
    const password = data.password;
    if (password && !ROOM_PASSWORD_PATTERN.test(password)) {
        return message.warning(ROOM_PASSWORD_PATTERN_TIP);
    }
    ws.emit("room.modify.password", {
        details: {
            pwd: password
        }
    });
    data.password = "";
}

function handleDissolveRoom() {
    dialog.warning({
        title: "解散房间",
        content: "你确定要解散该房间吗？(此操作不可逆)",
        positiveText: "解散",
        onPositiveClick: () => {
            ws.emit("room.dissolve", {
                details: {
                    rid: props.room.id
                }
            });
        }
    });
}

</script>

<template>
    <span @click="data.visible = true">设置</span>

    <drawer-modal v-model:show="data.visible">
        <div class="flex flex-col gap-5">
            <h2 class="text-center text-lg">修改房间信息</h2>

            <n-input-group>
                <n-input v-model:value="data.name" placeholder="房间名称"/>
                <n-button @click="handleModifyName">修改名称</n-button>
            </n-input-group>

            <n-input-group>
                <n-input v-model:value="data.url" placeholder="视频URL"/>
                <n-button @click="handlePlayVideo">切换视频</n-button>
            </n-input-group>

            <n-input-group>
                <n-input v-model:value="data.password" placeholder="房间密码" type="password"/>
                <n-button @click="handleModifyPassword">修改密码</n-button>
            </n-input-group>

            <div>
                <n-button type="error" @click="handleDissolveRoom">解散房间</n-button>
            </div>
        </div>
    </drawer-modal>
</template>

<style scoped>

</style>